<?php
/**
 * 文件管理
 * $Id: class.file.php 238 2011-01-13 08:53:47Z bwanglei@gmail.com $
 */

class awFile {
	/**
	 * 内部数据对象
	 * @var MySQL
	 */
	private $db;

	function __construct() {
		$this->db = MySQL::getInstance();
	}

	/**
	 * 删除某个文件
	 */
	function delete_file($id) {
		//从文件系统中删除
		$get_sql = 'SELECT * FROM `'.DB_PREFIX.'files` WHERE `id`='.$id;
		$result = $this->db->query($get_sql);
		$result = $this->db->fetch_array($result);
		$path_file = AW_ROOT.'/upload/'.$result['name'];
		//从数据库中删除
		$sql = 'DELETE FROM `'.DB_PREFIX.'files` WHERE `id`='.$id;
		$this->db->query($sql);
		//检测文件是否存在
		file_exists($path_file) or die("文件不存在！");
		if (!unlink($path_file)) return false;
	}

	/**
	 * 获取多个File从数据库
	 */
	function get_files($b='', $count_page=7) {
		if (!isset($b) || $b=='') {
			$sql = 'SELECT * FROM `'.DB_PREFIX.'files` ORDER BY `id` DESC LIMIT '.($count_page+1);
			$pre_sql = '';
		} else {
			$sql = 'SELECT * FROM `'.DB_PREFIX.'files` WHERE `id`<='.$b.' ORDER BY `id` DESC LIMIT '.($count_page+1);
			$pre_sql = 'SELECT * FROM `'.DB_PREFIX.'files` WHERE `id`>'.$b.' ORDER BY `id` ASC LIMIT '.$count_page;
		}
		$result_files = $this->db->query($sql);
		//取得next_bookmark
		$count_result = $this->db->num_rows($result_files);
		if ($count_result <= $count_page) {
			$next_bookmark = false;
		} else {
			mysql_data_seek($result_files, $count_result-1);
			$next_bookmark = $this->db->fetch_array($result_files);
			$next_bookmark = $next_bookmark['id'];
			mysql_data_seek($result_files,0);
		}
		//取得pre_bookmark
		if (isset($pre_sql) && $pre_sql!='') {
			$pre_files = $this->db->query($pre_sql);
			$count_pre = $this->db->num_rows($pre_files);
			if ($count_pre == 0) {
				$pre_bookmark == 0;
			} else {
				mysql_data_seek($pre_files, ($count_pre-1));
				$pre_bookmark = $this->db->fetch_array($pre_files);
				$pre_bookmark = $pre_bookmark['id'];
			}
		} else {
			$pre_bookmark = false;
		}

		//取得结果集合
		$files = array();
		while ($file = $this->db->fetch_array($result_files)) {
			$files[] = $file;
		}
		//删除最后一个多余的结果
		if (count($files)>$count_page) array_pop($files);
		return array($files, $pre_bookmark, $next_bookmark);
	}
}
